package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.model.result.StarInfoResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.IPushExtHandleService;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantThirdBaseInfo;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *  全授权
 */
@Service
public class CommonApiSMaskPushService implements IPushApiService,IPushApi2Service, IPushExtHandleService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMask = memberSourceInfo.getMobileMask();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobileMask", memberSourceInfo.getMobile().substring(0,8));
        paramMap.put("idCar", memberSourceInfo.getIdcard());
        paramMap.put("realname", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", 1);
        }else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        paramMap.put("huabei",memberSourceInfo.getHuabei());
        paramMap.put("shebao",memberSourceInfo.getShebao());
        paramMap.put("baitiao",memberSourceInfo.getBaitiao());
        paramMap.put("yuqi",memberSourceInfo.getYuqi());
        paramMap.put("house",memberSourceInfo.getHouse());
        paramMap.put("loanTime",memberSourceInfo.getLoanTime());
        paramMap.put("baoxian",memberSourceInfo.getBaoxian());
        paramMap.put("xueli",memberSourceInfo.getXueli());
        paramMap.put("car",memberSourceInfo.getCar());
        paramMap.put("shouru",memberSourceInfo.getShouru());
        paramMap.put("gongzuo",memberSourceInfo.getGongzuo());
        paramMap.put("yongtu",memberSourceInfo.getYongtu());
        if (StringUtils.isEmpty(memberSourceInfo.getWeili())){
            paramMap.put("weili", BaseTypeInfoEnum.WeiLi.wl001.getValue());
        }else {
            paramMap.put("weili",memberSourceInfo.getWeili());
        }
        if (StringUtils.isEmpty(memberSourceInfo.getXinyongka())){
            paramMap.put("xinyongka",BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            paramMap.put("xinyongka",memberSourceInfo.getXinyongka());
        }

        paramMap.put("gjj",memberSourceInfo.getGjj());
        paramMap.put("zhima",memberSourceInfo.getZhima());
        paramMap.put("outOrderNo", orderNo);
        paramMap.put("ip", memberSourceInfo.getReqIp());

        //加密
        String encrypt =  SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("requestNo", UUID.randomUUID().toString());
        bizMap.put("appCode",pushApiKeyParam.getApiCode());
        bizMap.put("tranData",encrypt);

        log.info("【全流程导量】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【全流程导量】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("respCode");
        String respMsg = resultObject.getString("respMsg");

        pushApiResult.setCode(respCode);
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (!StrUtil.equals(respCode, "200")) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }

        // 撞库成功之后，商户的机构数据存储
        JSONObject respData = resultObject.getJSONObject("respData");
        JSONArray md5List = respData.getJSONArray("md5List");
        String mobileMd5 = memberSourceInfo.getMobileMd5();
        if(MobileMd5IsInListUtils.isMobileMd5InList(md5List,mobileMd5)){
            //如果存在
            pushApiResult.setPushSuccess(false);
            pushApiResult.setCode(respCode+ "|" + "500");
            pushApiResult.setMessage(respMsg + "|" + mobileMd5 +"已存在");
            return pushApiResult;
        }

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setInfoObject(respData);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
            BigDecimal price = respData.getBigDecimal("price");//下游返回分润前价格
            if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceRight = typeRate.multiply(price);//分润后价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceRight);

        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save){
            pushApiResult.setPushSuccess(true);
        }else{
            pushApiResult.setMessage("保存撞库数据失败");
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        JSONObject bizMap = new JSONObject();
        bizMap.put("mobile", memberSourceInfo.getMobile());
        bizMap.put("idCar", memberSourceInfo.getIdcard());
        bizMap.put("realname", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1){
            bizMap.put("sex", 1);
        }else {
            bizMap.put("sex", 2);
        }
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("province",memberSourceInfo.getProvince());
        bizMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        bizMap.put("city",memberSourceInfo.getCity());
        bizMap.put("cityCode",memberSourceInfo.getCityCode());
        bizMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        bizMap.put("huabei",memberSourceInfo.getHuabei());
        bizMap.put("shebao",memberSourceInfo.getShebao());
        bizMap.put("baitiao",memberSourceInfo.getBaitiao());
        bizMap.put("yuqi",memberSourceInfo.getYuqi());
        bizMap.put("house",memberSourceInfo.getHouse());
        bizMap.put("loanTime",memberSourceInfo.getLoanTime());
        bizMap.put("baoxian",memberSourceInfo.getBaoxian());
        bizMap.put("xueli",memberSourceInfo.getXueli());
        bizMap.put("car",memberSourceInfo.getCar());
        bizMap.put("shouru",memberSourceInfo.getShouru());
        bizMap.put("gongzuo",memberSourceInfo.getGongzuo());
        bizMap.put("yongtu",memberSourceInfo.getYongtu());
        if (StringUtils.isEmpty(memberSourceInfo.getWeili())){
            bizMap.put("weili", BaseTypeInfoEnum.WeiLi.wl001.getValue());
        }else {
            bizMap.put("weili",memberSourceInfo.getWeili());
        }
        if (StringUtils.isEmpty(memberSourceInfo.getXinyongka())){
            bizMap.put("xinyongka",BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            bizMap.put("xinyongka",memberSourceInfo.getXinyongka());
        }
        bizMap.put("gjj",memberSourceInfo.getGjj());
        bizMap.put("zhima",memberSourceInfo.getZhima());
        bizMap.put("outOrderNo",orderNo);
        bizMap.put("ip",memberSourceInfo.getReqIp());


        MerchantThirdBaseInfo merchantThirdBaseInfo = merchantThirdBaseInfoService.selectEntityByOrderNo(orderNo);
        if (ObjectUtil.isEmpty(merchantThirdBaseInfo)){
            pushApiResult.setMessage("商户机构数据为空【pushId】" + orderNo);
            return pushApiResult;
        }
        bizMap.put("orderNo",merchantThirdBaseInfo.getOutOrderNo());
        bizMap.put("productId",merchantThirdBaseInfo.getProductId());

        String orderId = extJson.getString("orderId");
        String orderItemId = extJson.getString("orderItemId");
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        bizMap.put("protocolUrl", protocolUrl);

        //加密
        String encrypt = encrypt(JSON.toJSONString(bizMap), pushApiKeyParam.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestNo", UUID.randomUUID().toString());//请求序列号
        paramMap.put("appCode",pushApiKeyParam.getApiCode());//应用编号
        paramMap.put("tranData",encrypt);//业务参数

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        log.info("【全流程导量】导单开始【infoId】{}【infoName】{}【queryUrl】{}【bizMap】{}【paramMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【全流程导量】导单结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("respCode");
        String respMsg = resultObject.getString("respMsg");

        pushApiResult.setCode(respCode );
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(respCode );
        thirdInfoDTO.setRetMsg(respMsg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals(String.valueOf(respCode), "200")) {
            JSONObject respData = resultObject.getJSONObject("respData");
            String status = respData.getString("status");
            String message = respData.getString("message");
            thirdInfoDTO.setRetCode(respCode+"|"+status );
            thirdInfoDTO.setRetMsg(respMsg+"|"+message);
            if(StrUtil.equals(String.valueOf(status), "000")){
                thirdInfoDTO.setStatus("SUCCESS");
            }
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);

        if (StrUtil.equals(String.valueOf(respCode), "200")) {
            JSONObject respData = resultObject.getJSONObject("respData");
            String status = respData.getString("status");
            String message = respData.getString("message");
            pushApiResult.setCode(respCode+"|"+status);
            pushApiResult.setMessage(respMsg+"|"+message);
            if (StrUtil.equals(String.valueOf(status), "000")){
                //修改时间
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String encrypt(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key 为空 null");
            return null;
        }// 判断 Key 是否为 16 位
        if (sKey.length() != 16) {
            if(sKey.length()!=32){
                System.out.print("Key 不合法");
                return null;
            }
        }
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); // 此处使用 BASE64 做转码功能，同时能起到 2 次加密的作用。
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMask = memberSourceInfo.getMobileMask();
        if (StringUtils.isEmpty(mobileMask)){
            pushApiResult.setCode("301");
            pushApiResult.setMessage("掩码不存在,不进行撞库");
            return pushApiResult;
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mobileMask", mobileMask);
        paramMap.put("idCar", memberSourceInfo.getIdcard());
        paramMap.put("realname", memberSourceInfo.getRealname());
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", 1);
        }else {
            paramMap.put("sex", 2);
        }
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("province",memberSourceInfo.getProvince());
        paramMap.put("provinceCode",memberSourceInfo.getProvinceCode());
        paramMap.put("city",memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmount",memberSourceInfo.getLoanAmount());
        paramMap.put("huabei",memberSourceInfo.getHuabei());
        paramMap.put("shebao",memberSourceInfo.getShebao());
        paramMap.put("baitiao",memberSourceInfo.getBaitiao());
        paramMap.put("yuqi",memberSourceInfo.getYuqi());
        paramMap.put("house",memberSourceInfo.getHouse());
        paramMap.put("loanTime",memberSourceInfo.getLoanTime());
        paramMap.put("baoxian",memberSourceInfo.getBaoxian());
        paramMap.put("xueli",memberSourceInfo.getXueli());
        paramMap.put("car",memberSourceInfo.getCar());
        paramMap.put("shouru",memberSourceInfo.getShouru());
        paramMap.put("gongzuo",memberSourceInfo.getGongzuo());
        paramMap.put("yongtu",memberSourceInfo.getYongtu());
        if (StringUtils.isEmpty(memberSourceInfo.getWeili())){
            paramMap.put("weili", BaseTypeInfoEnum.WeiLi.wl001.getValue());
        }else {
            paramMap.put("weili",memberSourceInfo.getWeili());
        }
        if (StringUtils.isEmpty(memberSourceInfo.getXinyongka())){
            paramMap.put("xinyongka",BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            paramMap.put("xinyongka",memberSourceInfo.getXinyongka());
        }

        paramMap.put("gjj",memberSourceInfo.getGjj());
        paramMap.put("zhima",memberSourceInfo.getZhima());
        paramMap.put("outOrderNo", orderNo);
        paramMap.put("ip", memberSourceInfo.getReqIp());

        //加密
        String encrypt =  SecureUtil.aes(pushApiKeyParam.getApiSecret().getBytes()).encryptBase64(JSON.toJSONString(paramMap));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("requestNo", UUID.randomUUID().toString());
        bizMap.put("appCode",pushApiKeyParam.getApiCode());
        bizMap.put("tranData",encrypt);

        log.info("【上游全流程掩码导量】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【上游全流程掩码导量】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        String respCode = resultObject.getString("respCode");
        String respMsg = resultObject.getString("respMsg");

        pushApiResult.setCode(respCode);
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (!StrUtil.equals(respCode, "200")) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }

        // 撞库成功之后，商户的机构数据存储
        JSONObject respData = resultObject.getJSONObject("respData");

        JSONArray md5List = respData.getJSONArray("md5List");
        pushApiResult.setMd5List(md5List);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setInfoObject(respData);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
            BigDecimal price = respData.getBigDecimal("price");//下游返回分润前价格
            if (price == null || price.compareTo(new BigDecimal(0.00)) == -1){
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceRight = typeRate.multiply(price);//分润后价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceRight);

        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save){
            pushApiResult.setPushSuccess(true);
        }else{
            pushApiResult.setMessage("保存撞库数据失败");
        }

        return pushApiResult;
    }

    @Override
    public StarInfoResult handleStarInfo(MerchantBaseInfo merchantBaseInfo, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        StarInfoResult starInfoResult = new StarInfoResult();
        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);

        if (ObjectUtil.isEmpty(jsonObjectParamContent)) {
            return starInfoResult;
        }

        String mobileMd5 = jsonObjectParamContent.getString("mobileMd5");
        Integer startLevel = jsonObjectParamContent.getInteger("startLevel");
        starInfoResult.setMobileMd5(mobileMd5);
        starInfoResult.setStarLevel(startLevel);
        return starInfoResult;
    }
}
